//
//  HELCreditApplyVC.m
//  NursingAssociation
//
//  Created by wsj2015 on 2017/3/21.
//  Copyright © 2017年 wsj2015. All rights reserved.
//

#import "HELCreditApplyVC.h"
#import "HELCourseListModel.h"
#import "HELCourseCell.h"
#import "NHCourseDetailVC.h"
#import "BFPaperButton.h"
#import "Masonry.h"
@interface HELCreditApplyVC ()

@property(nonatomic, assign)BOOL isPickIng;

@property(nonatomic, strong)BFPaperButton *confirmBtn;
@property(nonatomic, strong)UIButton *pickeBtn;

@end

@implementation HELCreditApplyVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.tableView.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight - 64);
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.confirmBtn];
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view);
        make.top.equalTo(self.view);
        make.right.equalTo(self.view);
        make.bottom.equalTo(self.confirmBtn.mas_top);
        
    }];
    [self.confirmBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view);
        make.bottom.equalTo(self.view.mas_bottom).offset(44);
        make.right.equalTo(self.view);
        make.height.mas_equalTo(44);
    }];
    self.title = @"申请学分";
    self.isPickIng = NO;
    [self.tableView registerNib:[UINib nibWithNibName:@"HELCourseCell" bundle:nil] forCellReuseIdentifier:@"HELCourseCell"];
    weakSelf_define;
    
    UIButton *btn =[UIButton buttonWithType:UIButtonTypeSystem];
    [btn setTitle:@"选择" forState:UIControlStateNormal];
    [btn setTitle:@"取消" forState:UIControlStateSelected];
    [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(isBeginToPick) forControlEvents:UIControlEventTouchUpInside];
    btn.frame  =CGRectMake(0, 0, 39, 39);
    self.pickeBtn = btn;
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
    
//    [self.tableView wsj_HeaderRefreshBlock:^{
//        [weakSelf queryMayCreditApplyCourseList:YES];
//    }];
    [self.tableView wsj_FooterRefreshBlock:^{
       
            [weakSelf queryMayCreditApplyCourseList:NO];
        
    }];

     [self queryMayCreditApplyCourseList:YES];
}

- (BFPaperButton *)confirmBtn{
    if (!_confirmBtn) {
        _confirmBtn = [BFPaperButton buttonWithType:UIButtonTypeCustom];
        
        [_confirmBtn setTitle:@"申请学分" forState:UIControlStateNormal];
        [_confirmBtn setBackgroundColor:kMainColor];
        _confirmBtn.isRaised = YES;
        _confirmBtn.titleFont = [UIFont systemFontOfSize:17];
        [_confirmBtn addTarget:self action:@selector(confirmApply) forControlEvents:UIControlEventTouchUpInside];
    }
    return _confirmBtn;

}

- (void)confirmApply{

    
     NSArray<NSIndexPath *> *arr = [self.tableView indexPathsForSelectedRows];
    if (!arr.count) {
        cwqAlertMessage(@"至少选择一个课程~");
        return;
    }
    
  
    NSMutableArray *ids =[NSMutableArray array];
      [arr enumerateObjectsUsingBlock:^(NSIndexPath * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
          HELCourseListModel *model  = [self.dataArray objectAtIndex:obj.row];
          [ids addObject:model.id];
      }];
    
    if (ids.count) {
        [self applyRequest:ids];
    }

}

- (void)applyRequest:(NSArray *)courseIdArray{
  
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
 
    params[@"creditType"] =self.creditName;
    

    params[@"courseId"]  = [courseIdArray componentsJoinedByString:@","];
    cwqHud(self.view);
    weakSelf_define;
    [[HELNetworkManager sharedMg] POST:helApplyCredit parameters:params success:^(id responseObject) {
        [hud hide:YES];
        [weakSelf isBeginToPick];
        [weakSelf queryMayCreditApplyCourseList:YES];
       
        cwqHudSuccess(@"申请成功");
    } failure:^(NSString *err) {
         [hud hide:YES];
    }];
    

}



- (void)isBeginToPick{
    
   
//    if (!self.dataArray.count) {
//        cwqAlertMessage(@"暂无可以申请学分课程可以选择!");
//        return;
//    }
    
   self.isPickIng = !self.isPickIng;
   self.pickeBtn.selected = !self.pickeBtn.selected;
   [self.tableView setEditing:self.isPickIng animated:YES];
   [self showOrHideBtn];
   
  
}

- (void)showOrHideBtn{
   
    if (self.isPickIng) {
        
        [self.confirmBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.view);
            make.bottom.equalTo(self.view.mas_bottom).offset(0);
            make.right.equalTo(self.view);
            make.height.mas_equalTo(44);
        }];
        
    }else{
        [self.confirmBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.view);
            make.bottom.equalTo(self.view.mas_bottom).offset(44);
            make.right.equalTo(self.view);
            make.height.mas_equalTo(44);
        }];
    }
    [UIView animateWithDuration:.35 animations:^{
        [self.view layoutIfNeeded];
    }];

}


- (void)queryMayCreditApplyCourseList:(BOOL)isRecover{
  
    static NSUInteger page = 1;
    if (isRecover) {
        page =1;
    }else{
        page ++;
    }
    
    NSMutableDictionary *params =[NSMutableDictionary dictionary];
    params[@"page"] = @(page);
    params[@"rows"] = @(15);
    
    params[@"creditName"]  = self.creditName?self.creditName:@"";
    weakSelf_define;
    self.tableView.loading = YES;
    [[HELNetworkManager sharedMg] POST:helMayApplyCreditList parameters:params success:^(id responseObject) {
        [weakSelf.tableView.header endRefreshing];
        [weakSelf.tableView.footer endRefreshing];
        weakSelf.tableView.loading = NO;
        if ([responseObject[@"data"] isKindOfClass:[NSDictionary class]]) {
            
            if (isRecover) {
                [weakSelf.dataArray removeAllObjects];
            }
            NSInteger totalPage = 0;
            if ([responseObject[@"data"][@"totalPage"] isKindOfClass:[NSNull class]]) {
                
            }else{
                totalPage =[responseObject[@"data"][@"totalPage"] integerValue];
            }
            
            NSInteger currentPage = [responseObject[@"data"][@"page"] integerValue];
            if (currentPage>=totalPage) {
                [weakSelf.tableView.footer noticeNoMoreData];
            }else{
                [weakSelf.tableView.footer resetNoMoreData];
            }
            
            [weakSelf.dataArray addObjectsFromArray:[HELCourseListModel mj_objectArrayWithKeyValuesArray:responseObject[@"data"][@"data"]]];
            
            [weakSelf.tableView reloadData];
            
        }

      } failure:^(NSString *err) {
          [weakSelf.tableView.header endRefreshing];
          [weakSelf.tableView.footer endRefreshing];
          weakSelf.tableView.loading = NO;
      }];

}

- (void)viewDidLayoutSubviews{
  
    [super viewDidLayoutSubviews];

}


- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return UITableViewCellEditingStyleDelete|UITableViewCellEditingStyleInsert ;
}
- (BOOL)tableView:(UITableView *)tableView shouldIndentWhileEditingRowAtIndexPath:(NSIndexPath *)indexPath{
    return YES;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
//    return 20;
    return self.dataArray.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return  120;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    HELCourseCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HELCourseCell"];
    cell.courseListModel = self.dataArray[indexPath.row];
    cell.multipleSelectionBackgroundView = [UIView new];
    cell.tag_MycourseList = YES;
    cell.tintColor = kPinchColor;
    
    return cell;
    
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
  
    
    if (self.isPickIng) {
        return;
    }
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    HELCourseListModel *model = self.dataArray[indexPath.row];
    NHCourseDetailVC *vc =[NHCourseDetailVC new];
    vc.courseId = [model.id integerValue];
    
    [self.navigationController pushViewController:vc animated:YES];
    
}

@end
